package com.xw.echo.core.nacos;

import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.xw.echo.core.nacos.client.AddrsLocalCache;
import com.xw.echo.core.pool.ManagerConnectPool;
import com.xw.echo.core.register.HostAndPort;

import java.util.ArrayList;
import java.util.List;

public class ServiceEventListener implements EventListener {
    @Override
    public void onEvent(Event event) {
        NamingEvent namingEvent = (NamingEvent) event;
        String serviceName = namingEvent.getServiceName();
        List<HostAndPort> hostAndPorts = new ArrayList<>();
        List<String> newHostAndPorts = new ArrayList<>();
        List<Instance> instances = namingEvent.getInstances();
        for (Instance instance : instances){
            String ipAndPort = instance.getIp() + ":" + instance.getPort();
            newHostAndPorts.add(ipAndPort);
            System.out.println("  IP: " + instance.getIp() + ", Port: " + instance.getPort() + ", Weight: " + instance.getWeight() + ", Healthy: " + instance.isHealthy());
            hostAndPorts.add(new HostAndPort(instance.getIp(), instance.getPort()));
        }
        updateService(serviceName, hostAndPorts);
        ManagerConnectPool.getInstance().replaceConnectPool(newHostAndPorts, serviceName);
    }
    private void updateService(String serviceName, List<HostAndPort> hostAndPorts){
        AddrsLocalCache.add(serviceName, hostAndPorts);
    }

}
